/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.manager.channelHandler;

import com.icee.myth.manager.message.serverMessage.builder.ManagerMessageBuilder;
import com.icee.myth.common.messageQueue.ServerMessageQueue;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 * 服务器间通信，Deamon服务器发消息给Manager服务器的Handler
 * @author liuxianke
 */
public class DeamonToManagerHandler extends SimpleChannelUpstreamHandler {

    @Override
    public void channelConnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        // Add Deamon channel connected message to message queue
        ServerMessageQueue.queue().offer(ManagerMessageBuilder.buildDeamonConnectMessage(e.getChannel()));
    }

    @Override
    public void channelDisconnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        // Add Deamon channel close message to message queue
        ServerMessageQueue.queue().offer(ManagerMessageBuilder.buildDeamonCloseMessage(e.getChannel()));
    }

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        // TODO: 接收到从Deamon来的消息
        MLogger.getlogger().log(LogConsts.LOGTYPE_DEBUG, "Manager receive something from deamon.");
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getChannel().close();
    }

}
